/**
 * Created by gaoyj on 2018/6/28.
 */
window.onload = function (ev) {
    topbar.hide();
};
var myDate = new Date();
var month = myDate.getMonth() + 1;
var day = myDate.getDate();
if (month < 10) {
    month = "0" + month;
}
if (day < 10) {
    day = "0" + day;
}
var _start = myDate.getFullYear() + '-' + month + '-' + day + " 00:00:00";
var _end = myDate.getFullYear() + '-' + month + '-' + day + " 23:59:59";
$("#buyStartTime").val(_start);
$("#buyEndTime").val(_end);
laydate.render({
    elem: '#buyStartTime',
    type: 'datetime'

});
laydate.render({
    elem: '#buyEndTime'
    , type: 'datetime'
});


auditGet();
getStopOpenAutoAudit();

function auditGet() {
    $.ajax({
        type: "POST",
        url: "/finance/getAutoAuditStatus",
        success: function (data) {
            if (data) {
                $('#include').bootstrapToggle('on');
            } else {
                $('#include').bootstrapToggle('off');
            }
        },
    });
}

function getStopOpenAutoAudit() {
    $.ajax({
        type: "POST",
        url: "/finance/getStopOpenAutoAudit",
        success: function (data) {
            if (data) {
                $('#include2').bootstrapToggle('on');
            } else {
                $('#include2').bootstrapToggle('off');
            }
        }
    });
}
buttonShiro("export_Role");
var adminRole = roleCheck();
$('#dataTable').bootstrapTable({
    url: '/finance/findWithdrawRecordPage',
    height: $(window).height() - 200,
    pageSize: 30,
    pagination: true,
    pageList: [30, 50, 100],
    clickToSelect: true,
    singleSelect: true,
    queryParams: queryParams,
    uniqueId: 'id',
    queryParamsType: '',
    sidePagination: 'server',
    showFooter: true,
    detailView: true,
    detailFormatter: function (index, row) {
        return getLog(row.id);
    },
    responseHandler: function (res) {
        return {
            "total": res.total,
            "rows": res.resultList
        };
    },
    onClickRow: function (row) {
        if (row.userAccount != null && row.userAccount != '') {
            $("#account_field" + row.id).html(row.userAccount);
        }
    },
    columns: [
        {
            checkbox: true
        },
        {
            align: 'center',
            formatter: function (v, row, index) {
                return index + 1
            }
        }, {
            align: 'center',
            field: 'orderId',
            title: '申请订单号'
        }, {
            align: 'center',
            field: 'flowNo',
            title: '流水号'
        },
        {
            align: 'center',
            field: 'userAccount',
            title: '会员编号',
            formatter: function (v, o) {
                return copyAddon(v) + (adminRole == 1 ? v :userAccountHidden(o.userAccount, o.id));
            }
        },
        {
            align: 'center',
            field: 'userName',
            title: '会员名称'
        }, {
            align: 'center',
            field: 'certName',
            title: '认证姓名'
        }, {
            align: 'center',
            field: 'bankName',
            title: '提现渠道',
            formatter: function (v, row, index) {
                if (v == null || v == "") {
                    return "支付宝";
                } else {
                    return v
                }
            }
        }, {
            align: 'center',
            field: 'price',
            title: '提现金额',
            footerFormatter: priceFormatter
        }, {
            align: 'center',
            field: 'servicePrice',
            title: '手续费',
            footerFormatter: servicePriceFormatter
        }, {
            align: 'center',
            field: 'applytype',
            title: '提现类型',
            formatter: function (v, row, index) {
                return applyTypeFun[v];
            }
        }
        , {
            align: 'center',
            field: 'auditstate',
            title: '审核状态',
            formatter: function (v, row, index) {
                return auditStateFun[v];
            }
        }
        , {
            align: 'center',
            field: 'state',
            title: '提现状态',
            formatter: function (v, row, index) {
                return withdrawStateFun[v];
            }
        }, {
            align: 'center',
            field: 'startTime',
            title: '申请时间',
            formatter: function (v, row, index) {
                var modifyTime = v === null ? "-" : changeDateFormat(v)
                return modifyTime;
            }
        }, {
            align: 'center',
            field: 'endTime',
            title: '处理时间',
            formatter: function (v, row, index) {
                var modifyTime = v === null ? "-" : changeDateFormat(v)
                return modifyTime;
            }
        }
        , {
            align: 'center',
            field: 'bankNo',
            title: '提现账号'
        }, {
            align: 'center',
            field: 'bankName',
            title: '提现银行',
            formatter: function (v, row, index) {
                if (v === null || v === '') {
                    return '-';
                }
                return v;
            }
        }, {
            align: 'center',
            field: 'payBank',
            title: '打款账号',
            formatter: function (v, row, index) {
                if (v === null || v === '') {
                    return '-';
                }
                return v;
            }
        }, {
            align: 'center',
            field: 'remark',
            title: '备注'
        }, {
            field: 'FIELD', title: '操作', width: 136, align: 'center', formatter: function (v, o) {
                var options = "";
                if ((o.state == 4 ) && o.auditstate == 1) {//异常状态
                    options += "<a  href='javascript:jump(2," + o.id + "," + o.state + ")'  value=2>置成功</a>&nbsp;&nbsp;";
                    options += "<a  href='javascript:jump(3," + o.id + "," + o.state + ")' value=3>置失败</a>";
                } else if (o.state == 1 && o.auditstate == 1) {//处理中状态
                    options = "<a  href='javascript:jump(2," + o.id + "," + o.state + ")'  value=2>置成功</a>&nbsp;&nbsp;";
                    options += "<a  href='javascript:jump(3," + o.id + "," + o.state + ")' value=3>置失败</a>&nbsp;&nbsp;" +
                        "<a  href='javascript:jump(4," + o.id + "," + o.state + ")' value=4>置异常</a>";
                }
                return options;
            }
        }
    ],
});

function getLog(id) {
    $.ajax({
        type: "post",
        url: "/finance/queryWithdrawrLog?withdrawId=" + id + "&type=USER_WITHDRAWALS",
        async: false,
        success: function (data) {
            o = data;
        }
    });
    var str = '<table class="detail-table" style="width: 100%"><tr><td>操作时间</td><td>操作人</td><td>状态</td></tr>';
    for (var i = 0; i < o.length; i++) {

        if (o[i].withdrawId === undefined || o[i].withdrawId === null || o[i].withdrawId === '') {
            str += '<td>无</td>';
        } else {
            str += '<tr><td>' + format(o[i].operateTime) + '</td><td>' + o[i].admin + '</td><td>' + withdrawLogState[o[i].status] + '</td>';
        }
        str += '</tr>';
    }
    str += '</table>';
    return str;
}

function priceFormatter(data) {
    var sumProfit = 0;
    for (var i = 0; i < data.length; i++) {
        sumProfit = sumProfit + data[i].price;
    }
    return sumProfit.toFixed(2)
}

function servicePriceFormatter(data) {
    var sumProfit = 0;
    for (var i = 0; i < data.length; i++) {
        sumProfit = sumProfit + data[i].servicePrice;
    }
    return sumProfit.toFixed(2)
}

$("#search").click(function () {
    var timeAdd = new Date($("#buyStartTime").val());
    var timeEnd = new Date($("#buyEndTime").val());
    if (timeAdd > timeEnd) {
        layer.msg("开始时间不能大于结束时间");
        return false;
    }
    $("#dataTable").bootstrapTable("refresh");
});

function jump(status, id, oldStatus) {
    if (status == 2) {
        $("#updateStatusLabel").html("置成功")
    } else if (status == 3) {
        $("#updateStatusLabel").html("置失败")
    } else if (status == 4) {
        $("#updateStatusLabel").html("置异常")
    }
    $("#updateStatusModal").modal("show");
    $("#oldId").val(id)
    $("#oldStatus").val(oldStatus)
    $("#comment").val("");
    $("#targetStatus").val(status);
}

$("#updateStatusSubmit").click(function () {
    // var data = $('#dataTable').bootstrapTable("getSelections");
    // if (data === null || data.length === 0) {
    //     layer.msg("请选择要操作的订单");
    //     return;
    // }
    // var id = data[0].id;
    // var oldState = data[0].state;
    $.post("/finance/updateWithdrawState?remark=" + $("#comment").val() + "&state="
        + $("#targetStatus").val() + "&oldState=" + $("#oldStatus").val() + "&id=" + $("#oldId").val(), function (data) {
        if (data.success) {
            $("#dataTable").bootstrapTable("refresh");
            $("#updateStatusModal").modal("hide");
            layer.msg("操作成功");
        } else {
            layer.msg(data.message)
        }
    }).error(function (data) {
        layer.msg(data.message)
    });
});

function updateAuditStatus(v) {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows === null || rows.length === 0) {
        layer.msg("请选择要操作的订单");
        return;
    }
    var state = rows[0].auditstate;
    if (state != 0) {
        layer.msg("当前状态不允许修改！");
        return;
    }
    var title = "";
    if (v === 1) {
        title = "审核通过"
    } else if (v === 2) {
        title = "审核失败"
    }
    $.confirm({
        title: '确认!',
        content: '确定要给' + rows[0].userName + title + '吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/finance/checkWithdrawRecord",
                data: {
                    recordId: rows[0].id,
                    auditstate: v
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg("操作成功");
                    } else {
                        layer.msg(data.message)
                    }
                },
            });
        }
    });
}

$("#resetTransfer").click(function () {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows === null || rows.length === 0) {
        layer.msg("请选择要操作的订单");
        return;
    }
    var state = rows[0].state;
    // 异常
    if (state != 4) {
        layer.msg("只能处理异常订单！");
        return;
    }
    $.confirm({
        title: '确认!',
        content: '确定要给' + rows[0].userName + '再次转账吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/finance/resetTransfer",
                data: {
                    recordId: rows[0].id
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg("操作成功");
                    } else {
                        layer.msg(data.message)
                    }
                },
            });
        }
    });
})
$("#dealFail").click(function () {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows === null || rows.length === 0) {
        layer.msg("请选择要操作的订单");
        return;
    }
    $.confirm({
        title: '确认!',
        content: '确定要给' + rows[0].userName + '处理失败吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/finance/dealFail",
                data: {
                    recordId: rows[0].id
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        $("#dataTable").bootstrapTable("refresh");
                        layer.msg("操作成功");
                    } else {
                        layer.msg(data.message)
                    }
                },
            });
        }
    });
})
//开启关闭
$('#stopPro').click(function (e) {
    var status;
    e.stopPropagation();
    var remind = "";
    var isOn = $('#include').prop('checked');
    if (isOn) {
        remind = "关闭";
        status = 0
    } else {
        remind = "开启"
        status = 1
    }
    $.confirm({
        title: '确认!',
        content: '确定要' + remind + '自动审核吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/finance/changeAutoAuditStatus",
                data: {
                    status: status
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        layer.msg(data.message);
                        auditGet();
                    } else {
                        layer.msg(data.message);
                        auditGet();
                    }
                }
            })
        }
    })
})
//停止自动开启自动审核
$('#stopAutoAudit').click(function (e) {
    var status;
    e.stopPropagation();
    var remind = "";
    var isOn = $('#include2').prop('checked');
    if (isOn) {
        remind = "启动";
        status = 0
    } else {
        remind = "停止"
        status = 1
    }
    $.confirm({
        title: '确认!',
        content: '确定要' + remind + '自动吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/finance/stopOpenAutoAudit",
                data: {
                    status: status
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        layer.msg(data.message);
                        getStopOpenAutoAudit();
                    } else {
                        layer.msg(data.message);
                        getStopOpenAutoAudit();
                    }
                }
            })
        }
    })
})

function queryParams(params) {
    return {
        'pageUnit.size': params.pageSize,
        'pageUnit.page': params.pageNumber,
        userAccount: $.trim($("#userAccount").val()),
        certificateName: $.trim($("#certificateName").val()),
        orderId: $("#orderId").val(),
        flowNo: $("#flowNo").val(),
        remark: $("#remark").val(),
        state: $("#state").val(),
        withdrawChannel: $("#withdrawChannel").val(),
        price: $("#price").val(),
        applytype: $.trim($("#applytype").val()),
        startTime: $("#buyStartTime").val(),
        endTime: $("#buyEndTime").val(),
    };
}

//下载
$("#export").click(function () {
    window.location.href = "/finance/withdrawRecordDownLoad?" + $("#withdrawForm").serialize()
})